package com.xingfly.product.product.mq;

import com.xingfly.event.CustomRabbitListener;
import com.xingfly.inventory.sdk.event.InventoryChangedEvent;
import com.xingfly.product.product.Product;
import com.xingfly.product.product.ProductId;
import com.xingfly.product.product.ProductRepository;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.stereotype.Component;

/**
 * Created by SuperS on 2019/11/21.
 *
 * @author SuperS
 */
@Component
@CustomRabbitListener
public class ProductEventHandler {

    private ProductRepository productRepository;

    public ProductEventHandler(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    @RabbitHandler
    public void processInventoryChangedEvent(InventoryChangedEvent event) {
        Product product = productRepository.findById(ProductId.from(event.getProductId())).
                orElseThrow(() -> new RuntimeException("Product Not Found!"));
        product.updateInventory(event.getRemains());
        productRepository.save(product);
    }
}
